<?php
class RSAUtils{
//     https://www.zh30.com/php-sha1withrsa-sign-verify-pfx.html
//     http://www.jb51.net/article/95768.htm
    function sign($data,$keyPath,$password) {
        if(!file_exists($keyPath)) {
            echo 'privateKey not found';
            return '';
        }
        $certs = array();
        $pkcs12 = file_get_contents($keyPath);
        openssl_pkcs12_read($pkcs12, $certs, $password);
        if (!$certs) {
            echo 'privateKey load fail';
            return '';
        }
        $privateKey = $certs['pkey']; //根据实际情况键值可能不同
        $publicKey = $certs['cert'];//根据实际情况键值可能不同
        $binarySignature = '';
        
        openssl_sign($data, $signature, $certs['pkey']);
        return base64_encode($signature); 
    }
//     http://blog.csdn.net/leedaning/article/details/50820938
    function ecbEncrypt($data,$keyPath) {
        $fp1=fopen($keyPath,"r"); //你的公钥文件路径
        $public_key=fread($fp1,8192);
        fclose($fp1);
        $pu_key=openssl_pkey_get_public(file_get_contents($keyPath));//这个函数可用来判断公钥是否是可用的
        $encrypted = "";
        openssl_public_encrypt($data, $encrypted, $pu_key);//私钥加密
        $encrypted = base64_encode($encrypted);//加密后的内容通常含有特殊字符，需要编码转换下，在网络间通过url传输时要注意base64编码是否是url安全的
        return $encrypted;
    }
    function ecbDecrypt($data, $keyPath, $password) {
        $priv_key_id = openssl_get_privatekey(file_get_contents($keyPath), $password);
        $crypted = base64_encode($data);
        $decrypted = '';
        
        //通过$priv_key_id私钥解密，生成$decrypted
        $crypted = base64_decode($data);
        openssl_private_decrypt($crypted, $decrypted, $priv_key_id);
        echo 'rsa decrypt : '.$decrypted.'<br><br>';
        //从内存中释放私钥或公钥
        openssl_free_key($priv_key_id);
        return $decrypted;
    }
    
    function test($data,$privateKeyPath, $publicKeyPath, $password) {
        $priv_key_id = openssl_get_privatekey(file_get_contents($privateKeyPath), $password);
        $pub_key_id = openssl_get_publickey(file_get_contents($publicKeyPath));
        echo 'path : '.$privateKeyPath.'<br>'.$publicKeyPath.'<br>'.$priv_key_id.'  '.$pub_key_id;
        $crypted = '';
        $decrypted = '';
        openssl_public_encrypt($data, $crypted, $pub_key_id);
        $crypted = base64_encode($crypted);
        echo 'rsa encrypt : '.$crypted.'<br>';
        
        //通过$priv_key_id私钥解密，生成$decrypted
        $crypted = base64_decode($crypted);
        openssl_private_decrypt($crypted, $decrypted, $priv_key_id);
        echo 'rsa decrypt : '.$decrypted.'<br><br>';
        //从内存中释放私钥或公钥
        openssl_free_key($priv_key_id);
        openssl_free_key($pub_key_id);
        
    }
    
}
?>